package com.open.system.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.open.common.controller.BaseController;
import com.open.common.task.HuaDaoPost;
import com.open.common.utils.PageUtils;
import com.open.common.utils.Query;
import com.open.common.utils.R;
import com.open.loan.utils.HttpUtil;
import com.open.system.domain.LoanBankDO;
import com.open.system.domain.LoanJuxinliMMobileDO;
import com.open.system.domain.LoanJuxinliMTokenDO;
import com.open.system.domain.LoanUserDO;
import com.open.system.domain.rsp.RspMobileInfoModel;
import com.open.system.service.*;
import net.sf.json.JSONArray;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 手机运营商信息
 */
 
@Controller
@RequestMapping("/system/loanJuxinliMMobile")
public class LoanJuxinliMMobileController extends BaseController {
	@Autowired
	private LoanJuxinliMMobileService loanJuxinliMMobileService;
	
	@Autowired
	private LoanUserService userService;
	
	@Autowired
	private LoanBankService bankService;
	
	@Autowired
	private LoanJuxinliMTokenService loanJuxinliMTokenService;
	
	@Autowired
	private LoanApplyLogService loanApplyLogService;
	
	@Autowired
	private LoanAdminLogService loanAdminLogService;
	
	public static String client_secret="a0d730a9ebb4411f881b52f5e6d5361a";
	public static String access_token="6aa02e8304cc4ed0abe34b111bf5354f";
	
	@GetMapping()
	@RequiresPermissions("system:loanJuxinliMMobile:loanJuxinliMMobile")
	String LoanJuxinliMMobile(){
	    return "system/loanJuxinliMMobile/loanJuxinliMMobile";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("system:loanJuxinliMMobile:loanJuxinliMMobile")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<LoanJuxinliMMobileDO> loanJuxinliMMobileList = loanJuxinliMMobileService.list(query);
		int total = loanJuxinliMMobileService.count(query);
		PageUtils pageUtils = new PageUtils(loanJuxinliMMobileList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("system:loanJuxinliMMobile:add")
	String add(){
	    return "system/loanJuxinliMMobile/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("system:loanJuxinliMMobile:edit")
	String edit(@PathVariable("id") Long id,Model model){
		LoanJuxinliMMobileDO loanJuxinliMMobile = loanJuxinliMMobileService.get(id);
		model.addAttribute("loanJuxinliMMobile", loanJuxinliMMobile);
	    return "system/loanJuxinliMMobile/edit";
	}
	
	
	@GetMapping("/mobileInfo/{id}")
	@RequiresPermissions("system:loanJuxinliMMobile:mobileInfo")
	String getMobileInfo(@PathVariable("id") Long id, Model model, HttpServletRequest request) {
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("userId",id);
		LoanUserDO user=userService.get(id);
		if(user.getRealName()==null || user.getRealName()==""){
			user.setRealName("未实名");
		}
		List<LoanJuxinliMMobileDO>mobileList =loanJuxinliMMobileService.list(map);
		List<RspMobileInfoModel>infomodels=new ArrayList<RspMobileInfoModel>();
		if(mobileList!=null && mobileList.size()>0){
			LoanJuxinliMMobileDO mobileDo=mobileList.get(0);
			
			//--操作日志--开始--
			String shopId=getUser().getEmail();
			String adminName=getUser().getName();
			String Module="运营商认证";
			String detail="查看了【"+mobileDo.getRealName()+"】的通话记录";
			loanAdminLogService.saveLog(shopId, adminName, Module, detail);
			//--操作日志--结束--
			
			JSONObject jsonObject =JSONObject.parseObject(mobileDo.getJsonData());
			if("true".equals(jsonObject.getString("success"))){
				String raw_data=jsonObject.getString("raw_data");
				JSONObject jsonRawData =JSONObject.parseObject(raw_data);
				String members=jsonRawData.getString("members");
				JSONObject jsonMembers =JSONObject.parseObject(members);
				if("success".equals(jsonMembers.getString("status")) && "31200".equals(jsonMembers.getString("error_code"))){
					String transactions=jsonMembers.getString("transactions");
					JSONArray arrayTransactions = JSONArray.fromObject(transactions);
					for (int i = 0; i < arrayTransactions.size(); i++) {
						net.sf.json.JSONObject jsonTransactions = arrayTransactions.getJSONObject(i);
						String calls=jsonTransactions.getString("calls");
						JSONArray callsArrays = JSONArray.fromObject(calls);
						 System.out.println(callsArrays.size());
						 for (int j = 0; j < callsArrays.size(); j++) {
							 RspMobileInfoModel infomodel=new RspMobileInfoModel();
							 net.sf.json.JSONObject info = callsArrays.getJSONObject(j);
							 String start_time=String.valueOf(info.get("start_time"));//通话时间
							 String init_type=String.valueOf(info.get("init_type"));//呼叫类型
							 String use_time=String.valueOf(info.get("use_time"));//通话时长（秒）
							 String place=String.valueOf(info.get("place"));//通话地点
							 String other_cell_phone=String.valueOf(info.get("other_cell_phone"));//对方号码
							 String cell_phone=String.valueOf(info.get("cell_phone"));//本机号码
							 //String call_type=info.getString("call_type");//通话类型
							 String call_type=String.valueOf(info.get("call_type"));
							 
							 infomodel.setCall_type(call_type);
							 infomodel.setCell_phone(cell_phone);
							 infomodel.setInit_type(init_type);
							 infomodel.setOther_cell_phone(other_cell_phone);
							 infomodel.setPlace(place);
							 infomodel.setStart_time(start_time);
							 infomodel.setUse_time(use_time);
							 infomodels.add(infomodel);
							 Collections.sort(infomodels);						
						}
					}
				}else if("success".equals(jsonMembers.getString("status")) && "31204".equals(jsonMembers.getString("error_code"))){
					List<LoanJuxinliMTokenDO>mTokenDOs=loanJuxinliMTokenService.list(map);
					if(mTokenDOs!=null && mTokenDOs.size()>0){
						LoanJuxinliMTokenDO mTokenDO=mTokenDOs.get(0);
						
						LoanBankDO bankDo=null;
						System.out.println("2");
						map.put("hasempty", request.getParameter("downType"));
						List<LoanBankDO>bankLists=bankService.list(map);
						map.remove("hasempty");
						/*for (int i = 0; i <bankLists.size(); i++) {
							bankDo=bankLists.get(0);
						}*/
						if(bankLists!=null && bankLists.size()>0){
							bankDo=bankLists.get(0);
						}
						String url="https://www.juxinli.com/api/access_raw_data_by_token";
						Map<String, String> params=new HashMap<String, String>();
						params.put("client_secret",client_secret);
						params.put("access_token",access_token);
						params.put("token",mTokenDO.getToken());
						String returnJson=HttpUtil.sendGet(url, params);
						List<LoanJuxinliMMobileDO> mobileLists=loanJuxinliMMobileService.list(map);
						if(mobileLists!=null && mobileLists.size()>0){
							LoanJuxinliMMobileDO mobileDO=mobileLists.get(0);
							mobileDO.setJsonData(returnJson);
							mobileDO.setUserId(bankDo.getUserId());
							mobileDO.setRealName(bankDo.getRealName());
							loanJuxinliMMobileService.update(mobileDO);
						}
						
					}
				}
			}
		}
		model.addAttribute("infomodels", infomodels);
		model.addAttribute("user", user);
		if ("1".equals(request.getParameter("downType"))) {
			return "system/loanJuxinliMMobile/mobileInfoDownLoad";
		}
	    return "system/loanJuxinliMMobile/mobileInfo";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("system:loanJuxinliMMobile:add")
	public R save( LoanJuxinliMMobileDO loanJuxinliMMobile){
		if(loanJuxinliMMobileService.save(loanJuxinliMMobile)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("system:loanJuxinliMMobile:edit")
	public R update( LoanJuxinliMMobileDO loanJuxinliMMobile){
		loanJuxinliMMobileService.update(loanJuxinliMMobile);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("system:loanJuxinliMMobile:remove")
	public R remove( Long id){
		if(loanJuxinliMMobileService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("system:loanJuxinliMMobile:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		loanJuxinliMMobileService.batchRemove(ids);
		return R.ok();
	}
	
}
